import { SetStateAction, useRef, useState } from "react";
import { List, Input, Button, Toast } from "zarm";
import Icon from "@/config";
import "./index.less";
import { validateEmail } from "@/utils/verify";
import { getCaptcha, register, login } from "@/utils/request";
import { useNavigate } from "react-router-dom";

import cx from "classnames";

export interface LoginUser {
  username: string;
  password: string;
}

export interface RegisterUser extends LoginUser {
  captcha: string;
  confirmPassword: string;
}

export default function Login() {
  const [type, setType] = useState("login"); // 登录注册类型
  const [username, setUsername] = useState<string>(""); // 账号
  const [captcha, setCaptcha] = useState<string>(""); // 验证码
  const [password, setPassword] = useState<string>(""); // 密码
  const [confirmPassword, setConfirmPassword] = useState<string>(""); // 确认密码

  const captchaRef = useRef<HTMLInputElement>(null);

  const navigate = useNavigate();

  const handleGetCaptcha = async () => {
    // 验证用户名是否为空
    if (!username) {
      Toast.show("请输入邮箱作为用户名");
      return;
    }
    // 验证用户名是否为邮箱格式
    if (!validateEmail(username)) {
      Toast.show("请输入正确的邮箱");
      return;
    }

    const res = await getCaptcha(username);
    if (res.status == 200 || res.status == 201) {
      Toast.show("验证码已发送成功");
    }
  };

  const Submit = async () => {
    // 验证用户名是否为空
    if (!username) {
      Toast.show("请输入邮箱作为用户名");
      return;
    }
    // 验证用户名是否为邮箱格式
    if (!validateEmail(username)) {
      Toast.show("请输入正确的邮箱");
      return;
    }
    // 验证验证码是否为空
    if (!captcha && type == "register") {
      Toast.show("请输入验证码");
      return;
    }
    // 验证密码是否为空
    if (!password) {
      Toast.show("请输入密码");
      return;
    }
    // 验证两次密码是否一致
    if (password !== confirmPassword && type == "register") {
      Toast.show("两次密码不一致，请重新输入");
      return;
    }

    if (type == "login") {
      const res = await login({ username, password });

      if (res.status == 200 || res.status == 201) {
        localStorage.setItem("access_token", res.data.access_token || "");
        localStorage.setItem("refresh_token", res.data.refresh_token || "");
        Toast.show("登录成功");
        setTimeout(() => {
          navigate("/");
        }, 1000);
      }
    } else {
      const res = await register({
        username,
        captcha,
        password,
        confirmPassword,
      });
      if (res.status == 200 || res.status == 201) {
        Toast.show("注册成功");
        setType("login");
        setCaptcha("");
        setConfirmPassword("");
      }
    }
  };

  return (
    <div className="auth">
      <div className="head" />
      <div className="tab">
        <span
          className={cx({ avtive: type == "login" })}
          onClick={() => setType("login")}
        >
          登录
        </span>
        <span
          className={cx({ avtive: type == "register" })}
          onClick={() => setType("register")}
        >
          注册
        </span>
      </div>
      <div className="form">
        <List bordered={false}>
          <List.Item prefix={<Icon type="icon-youxiang" />}>
            <Input
              placeholder="请输入邮箱作为用户名"
              value={username}
              onChange={(e: { target: { value: SetStateAction<string> } }) =>
                setUsername(e.target.value)
              }
            />
          </List.Item>
          {type == "register" ? (
            <List.Item prefix={<Icon type="icon-yanzhengma" />}>
              <Input
                ref={captchaRef}
                placeholder="请输入验证码"
                value={captcha}
                onChange={(e: { target: { value: SetStateAction<string> } }) =>
                  setCaptcha(e.target.value)
                }
              />
              <Button
                size="xs"
                className="get"
                theme="primary"
                onClick={() => handleGetCaptcha()}
              >
                获取验证码
              </Button>
            </List.Item>
          ) : null}
          <List.Item prefix={<Icon type="icon-mima" />}>
            <Input
              placeholder="请输入密码"
              type="password"
              value={password}
              onChange={(e: { target: { value: SetStateAction<string> } }) =>
                setPassword(e.target.value)
              }
            />
          </List.Item>
          {type == "register" ? (
            <List.Item prefix={<Icon type="icon-mima" />}>
              <Input
                placeholder="请再次输入密码"
                type="password"
                value={confirmPassword}
                onChange={(e: { target: { value: SetStateAction<string> } }) =>
                  setConfirmPassword(e.target.value)
                }
              />
            </List.Item>
          ) : null}
        </List>
      </div>
      <div className="operation">
        <Button block theme="primary" onClick={Submit}>
          {type == "login" ? "登录" : "注册"}
        </Button>
      </div>
    </div>
  );
}
